package com.mzz.esdemo.handler;

import com.mzz.esdemo.common.constant.EsConstant;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import static com.mzz.esdemo.parser.EsResponseParser.forEachHits;

/**
 * Why
 * 2022-01-03
 */
public class EsSearchAfterHandler {
    private static final String UID = "_id";

    /**
     * Search for hit.
     *
     * @param searchRequest the search request
     * @param consumer      the consumer
     */
    public static void searchForHit(RestHighLevelClient client, SearchRequest searchRequest,
                                    Consumer<SearchHit> consumer) throws IOException {
        searchForResponse(client, searchRequest, searchResponse -> forEachHits(searchResponse, consumer));
    }

    /**
     * Search for response.
     *
     * @param searchRequest the search request
     * @param consumer      the consumer
     */
    public static void searchForResponse(RestHighLevelClient client, SearchRequest searchRequest,
                                         Consumer<SearchResponse> consumer) throws IOException {
        System.out.println("--------------------使用search_after搜索文档---------------------");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //设置查询大小
        searchSourceBuilder.size(100);
        //设置唯一排序值定位
/*        searchSourceBuilder.sort(UID, SortOrder.ASC);*/
        searchSourceBuilder.sort("_id", SortOrder.ASC);
        searchRequest.source(searchSourceBuilder);

        List<Map<String, Object>> result = new ArrayList<>();

        //3、发送请求
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        do {
            System.out.println("==========================================");
            for (SearchHit hit : searchResponse.getHits().getHits()) {
                //获取需要数据
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                result.add(sourceAsMap);
                System.out.println("返回的数据"+sourceAsMap.get("id"));
            }
            System.out.println("==========================================");
            //取得最后的排序值sort,用于记录下次将从这个地方开始取数
            SearchHit[] hits = searchResponse.getHits().getHits();
            Object[] lastNum = hits[hits.length-1].getSortValues();
            System.out.println("返回的参数"+lastNum[0]);
            //设置searchAfter的最后一个排序值
            searchSourceBuilder.searchAfter(lastNum);
            searchRequest.source(searchSourceBuilder);

            //进行下次查询
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        } while (searchResponse.getHits().getHits().length != 0);
        System.out.println("查询的总条数" + result.size());
/*        System.out.print(result);*/
       /* if (searchRequest == null || consumer == null) {
            return;
        }
        SearchSourceBuilder sourceBuilder = searchRequest.source();
        // sourceBuilder.size(100); //在构建查询条件时，即可设置大小
        //设置排序字段
        sourceBuilder.sort(UID, SortOrder.ASC);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        while (searchHits.length > 0) {
            consumer.accept(searchResponse);
            SearchHit last = searchHits[searchHits.length - 1];
            System.out.println("返回的searchAfter"+last.getSortValues());
            sourceBuilder.searchAfter(last.getSortValues());
            SearchResponse searchResponses = client.search(searchRequest, RequestOptions.DEFAULT);
            //搜索结果
            SearchHits hitss = searchResponses.getHits();
            //匹配到的总记录数
            *//*        long totalHits = hits.getTotalHits();*//*
            //得到匹配度高的文档
            SearchHit[] searchHitss = hitss.getHits();
            for (SearchHit hit : searchHitss) {
                //文档的主键
                String id = hit.getId();
                //源文档内容
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                String name = (String) sourceAsMap.get("name");
                System.out.println(name);
            }
        }*/
    }
    public static SearchHit[] searchAfter(RestHighLevelClient client, Object[] objects) throws IOException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.termQuery("name", "张三"));
        sourceBuilder.size(100);
        sourceBuilder.sort("name", SortOrder.DESC);
        sourceBuilder.sort("_id", SortOrder.DESC);
        if(!objects[1].toString().equals("start") && !objects[1].toString().equals("start")) {
            sourceBuilder.searchAfter(objects);
        }
        SearchRequest searchRequest = new SearchRequest();
  /*      searchRequest.indices("phonebills");*/
        searchRequest.source(sourceBuilder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        return hits;
    }
}
